package gui;

import java.awt.Component;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashMap;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import containers.StudentContainer;
import dbadapters.ChangeStudentdb;
import dbadapters.checkConnection;
import entities.FinancialInfo;
import entities.Loan;
import entities.Student;

/**
 * 
 * @author Diego Davila did074 loads the different panels that conforms this
 *         main panel, receives the frame to be mount in and the Id of the
 *         student to be displayed (info). check the information given by the
 *         user and make the necessary changes in the container and the Data
 *         Base
 * 
 */
public class EditPersonalInfoPanel extends JPanel {

	protected PersonalInfoPanel lpanel;
	protected StudentInfoPanel rpanel;
	protected FinancialInfoPanel lpanel2;
	protected LoanInfoPanelModified rpanel2;
	private JFrame myFrame;
	private Student std;
	public int Id;

	/*
	 * Loads all the panels in the frameRead the information of the specified
	 * student and displayit in the text boxes
	 */
	public EditPersonalInfoPanel(JFrame frame, int id) {

		myFrame = frame;

		Id = id;
		lpanel = new PersonalInfoPanel();
		lpanel.setMaximumSize(lpanel.getPreferredSize());
		lpanel.setAlignmentX(Component.LEFT_ALIGNMENT);
		lpanel.setAlignmentY(Component.TOP_ALIGNMENT);
		add(lpanel);

		rpanel = new StudentInfoPanel();
		rpanel.setMaximumSize(rpanel.getPreferredSize());
		rpanel.setAlignmentX(Component.RIGHT_ALIGNMENT);
		rpanel.setAlignmentY(Component.TOP_ALIGNMENT);
		add(rpanel);

		lpanel2 = new FinancialInfoPanel();
		lpanel2.setMaximumSize(lpanel2.getPreferredSize());
		lpanel2.setAlignmentX(Component.LEFT_ALIGNMENT);
		lpanel2.setAlignmentY(Component.BOTTOM_ALIGNMENT);
		add(lpanel2);

		rpanel2 = new LoanInfoPanelModified();
		rpanel2.setMaximumSize(rpanel2.getPreferredSize());
		rpanel2.setAlignmentX(Component.RIGHT_ALIGNMENT);
		rpanel2.setAlignmentY(Component.BOTTOM_ALIGNMENT);
		add(rpanel2);

		JButton apply = new JButton("Apply");
		apply.setAlignmentY(Component.BOTTOM_ALIGNMENT);

		add(apply);

		ApplyListener listener = new ApplyListener();
		apply.addActionListener(listener);

		std = null;
		HashMap<Integer, Student> students = StudentContainer.dictionary();

		if (students.containsKey(id) == true)
			std = students.get(id);

		lpanel.nameField.setValue(std.getName());
		lpanel.birthdateField.setValue(std.getBirthdateAsString());
		lpanel.addressField.setValue(std.getAddress());
		lpanel.phonenumberField.setValue(std.getPhoneNumber());
		lpanel.emailField.setValue(std.getEmail());
		rpanel.collegeField.setValue(std.getInstitution());
		if (std.getIsCitizen())
			rpanel.citizenCheck.doClick();
		rpanel.sinField.setValue(std.getSIN());
		lpanel2.personalField.setValue(Float.toString(std.getFinances()
				.getPersonalIncome()));
		lpanel2.householdField.setValue(Float.toString(std.getFinances()
				.getHouseholdIncome()));
		lpanel2.taxField.setValue(Float.toString(std.getFinances()
				.getTaxableEarnings()));
		lpanel2.childField.setValue(Float.toString(std.getFinances()
				.getChildSupport()));
		lpanel2.scholarField.setValue(Float.toString(std.getFinances()
				.getScholarship()));
		lpanel2.monthlyExpensesField.setValue(Float.toString(std.getFinances()
				.getMonthlyExpenses()));
		rpanel2.amountField.setValue(Double.toString(std.getLoan()
				.getAmountRequested()));
		rpanel2.passwordField.setValue((std.getPassword()));

	}

	/*
	 * Apply Button action First checks if all the information provided by the
	 * user is in the right format and if is it make the changes into the
	 * container and modify the Data Base, if is not it will display a messge
	 * box indicating where does the error is
	 */
	private class ApplyListener implements ActionListener {

		@Override
		public void actionPerformed(ActionEvent event) {
			// sort out filled out info to create a new student and place
			// him/her in container

			boolean isValid = true; // manage if input to application form is
			// valid or not
			String errorString = ""; // error message if needed

			String studentName = lpanel.nameField.getValueAsString();
			String remainingJunk = studentName.replaceAll("[a-zA-Z ]", ""); // check
			// if
			// input
			// is
			// alphabetic
			if (remainingJunk.length() > 0 || studentName.length() == 0) {
				errorString += "Invalid input for Name\n";
				isValid = false;
			}

			// get birthdate info in format MM/dd/yyyy
			String studentBirthdate = lpanel.birthdateField.getValueAsString();
			remainingJunk = studentBirthdate.replaceAll("[0-9/]", "");
			// check for proper format
			boolean isValidDate = studentBirthdate
					.matches("[0-1][0-9]/[0-3][0-9]/[0-2][90][0-9][0-9]");
			if (!isValidDate || remainingJunk.length() > 0) {
				errorString += "Invalid input for birthdate, should be mm/dd/yyyy\n";
				isValid = false;
			}

			String studentAddress = lpanel.addressField.getValueAsString();
			remainingJunk = studentAddress.replaceAll("[a-zA-Z.0-9 ]", "");
			if (remainingJunk.length() > 0 || studentAddress.length() == 0) {
				errorString += "Invalid input for Address\n";
				isValid = false;
			}

			String studentPhone = lpanel.phonenumberField.getValueAsString();
			remainingJunk = studentPhone.replaceAll("[0-9 ()-]", "");
			if (remainingJunk.length() > 0 || studentPhone.length() == 0) {
				errorString += "Invalid input for Phone Number\n";
				isValid = false;
			}

			String studentEmail = lpanel.emailField.getValueAsString();
			remainingJunk = studentEmail.replaceAll("[a-zA-Z0-9.@()-]", "");
			if (remainingJunk.length() > 0 || studentEmail.length() == 0) {
				errorString += "Invalid input for e-mail\n";
				isValid = false;
			}

			String studentCollege = rpanel.collegeField.getValueAsString();
			remainingJunk = studentCollege.replaceAll("[a-zA-Z ]", ""); // check
			// if
			// input
			// is
			// alphabetic
			if (remainingJunk.length() > 0 || studentCollege.length() == 0) {
				errorString += "Invalid input for College enrolled at\n";
				isValid = false;
			}

			boolean studentCitizen = rpanel.citizenCheck.isSelected();

			// now get proper enumerated value for marital status
			String studentMaritalName = rpanel.maritalBox.getSelection();
			studentMaritalName = studentMaritalName.toUpperCase();
			Student.maritalStatuses studentMarital = Student.maritalStatuses.SINGLE;
			if (studentMaritalName.contentEquals("SINGLE")) {
				studentMarital = Student.maritalStatuses.SINGLE;
			} else if (studentMaritalName.contentEquals("MARRIED")) {
				studentMarital = Student.maritalStatuses.MARRIED;
			} else if (studentMaritalName.contentEquals("COMMONLAW")) {
				studentMarital = Student.maritalStatuses.COMMONLAW;
			}

			// do a similar process for mother/father education levels
			String studentFatherString = rpanel.fatherBox.getSelection();
			studentFatherString = studentFatherString.toUpperCase();
			Student.education studentFather = Student.education.NONE;
			if (studentFatherString.contentEquals("DEGREE")) {
				studentFather = Student.education.DEGREE;
			} else if (studentFatherString.contentEquals("DIPLOMA")) {
				studentFather = Student.education.DIPLOMA;
			} else if (studentFatherString.contentEquals("HIGH SCHOOL")) {
				studentFather = Student.education.HIGH_SCHOOL;
			}

			// do a similar process for mother/father education levels
			String studentMotherString = rpanel.motherBox.getSelection();
			studentMotherString = studentMotherString.toUpperCase();
			Student.education studentMother = Student.education.NONE;
			if (studentMotherString.contentEquals("DEGREE")) {
				studentMother = Student.education.DEGREE;
			} else if (studentMotherString.contentEquals("DIPLOMA")) {
				studentMother = Student.education.DIPLOMA;
			} else if (studentMotherString.contentEquals("HIGH SCHOOL")) {
				studentMother = Student.education.HIGH_SCHOOL;
			}

			String studentSIN = rpanel.sinField.getValueAsString();
			remainingJunk = studentSIN.replaceAll("[0-9]", ""); // check if
			// input is
			// numeric
			if (studentSIN.length() != 9) {
				errorString += "student SIN must be 9 digits long\n";
				isValid = false;
			} else if (remainingJunk.length() > 0 || studentSIN.length() == 0) {
				errorString += "Invalid input for student SIN\n";
				isValid = false;
			}

			float studentPersonalIncome = 0;
			try {
				studentPersonalIncome = lpanel2.personalField.getValueAsFloat();
			} catch (NumberFormatException e) {
				isValid = false;
				errorString += e.getMessage() + "\n";
				studentPersonalIncome = 0;
			}

			if (studentPersonalIncome < 0) {
				isValid = false;
				errorString += "Personal Income must be positive\n";
			}

			float studentHouseholdIncome = 0;
			try {
				studentHouseholdIncome = lpanel2.householdField
						.getValueAsFloat();
			} catch (NumberFormatException e) {
				isValid = false;
				errorString += e.getMessage() + "\n";
				studentHouseholdIncome = 0;
			}

			if (studentHouseholdIncome < 0) {
				isValid = false;
				errorString += "Household Income must be positive\n";
			}

			float studentTaxIncome = 0;
			try {
				studentTaxIncome = lpanel2.taxField.getValueAsFloat();
			} catch (NumberFormatException e) {
				isValid = false;
				errorString += e.getMessage() + "\n";
				studentTaxIncome = 0;
			}

			if (studentTaxIncome < 0) {
				isValid = false;
				errorString += "Taxable Income must be positive\n";
			}

			float studentChildSupport = 0;
			try {
				studentChildSupport = lpanel2.childField.getValueAsFloat();
			} catch (NumberFormatException e) {
				isValid = false;
				errorString += e.getMessage() + "\n";
				studentChildSupport = 0;
			}

			if (studentChildSupport < 0) {
				isValid = false;
				errorString += "Child Support must be positive\n";
			}

			float studentScholarship = 0;
			try {
				studentScholarship = lpanel2.scholarField.getValueAsFloat();
			} catch (NumberFormatException e) {
				isValid = false;
				errorString += e.getMessage() + "\n";
				studentScholarship = 0;
			}

			if (studentScholarship < 0) {
				isValid = false;
				errorString += "Scholarship must be positive\n";
			}

			float studentMonthlyExpenses = 0;
			try {
				studentMonthlyExpenses = lpanel2.monthlyExpensesField
						.getValueAsFloat();
			} catch (NumberFormatException e) {
				isValid = false;
				errorString += e.getMessage() + "\n";
				studentMonthlyExpenses = 0;
			}

			if (studentMonthlyExpenses < 0) {
				isValid = false;
				errorString += "Monthly Expenses must be positive\n";
			}

			float studentRequestedAmount = 0;
			try {
				studentRequestedAmount = rpanel2.amountField.getValueAsFloat();
			} catch (NumberFormatException e) {
				isValid = false;
				errorString += e.getMessage() + "\n";
				studentRequestedAmount = 0;
			}

			if (studentRequestedAmount < 0) {
				isValid = false;
				errorString += "Requested Amount must be positive\n";
			}

			String studentPassword = "";
			studentPassword = rpanel2.passwordField.getValueAsString();
			if (studentPassword.length() == 0) {
				isValid = false;
				errorString += "You must enter a password\n";
			}

			if (!isValid) {
				JOptionPane.showMessageDialog(myFrame, errorString);
			} else {
				// student and loan are ready to be built and placed into the
				// system

				std.setAddress(studentAddress);
				std.setBirthdate(studentBirthdate);
				std.setCitizenship(studentCitizen);
				std.setEmail(studentEmail);
				std.setFatherEducation(studentFather);
				std.setInstitution(studentCollege);
				std.setMaritalStatus(studentMarital);
				std.setMotherEducation(studentMother);
				std.setName(studentName);
				std.setPhoneNumber(studentPhone);
				std.setSIN(studentSIN);

				FinancialInfo myFinances = std.getFinances();
				myFinances.setChildSupport(studentChildSupport);
				myFinances.setHouseholdIncome(studentHouseholdIncome);
				myFinances.setPersonalIncome(studentPersonalIncome);
				myFinances.setScholarship(studentScholarship);
				myFinances.setTaxableEarnings(studentTaxIncome);
				myFinances.setMonthlyExpenses(studentMonthlyExpenses);

				std.setFinances(myFinances);

				Loan newLoan = std.getLoan();
				newLoan.setAmountRequested(studentRequestedAmount);
				std.setLoan(newLoan);

				// update student in db if possible
				checkConnection c = new checkConnection();

				if (c.isConnectionValid()) {
					new ChangeStudentdb(std);
				} else {
					System.out.println(c.getErrorMessage());
				}

				JOptionPane.showMessageDialog(myFrame, "Success!");
				myFrame.setVisible(false);
			}

		}
	}

	private static final long serialVersionUID = 1L;
}